package org.xxpay.pay.channel.shengyu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.xxpay.common.bean.result.PayException;
import org.xxpay.common.exception.PayErrorException;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.http.UriVariables;
import org.xxpay.common.unify.AbstractPaymentConfig;
import org.xxpay.common.util.DateUtils;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.channel.shengfutong.SftpayConfig;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Package org.xxpay.pay.channel.shengfutong
 * @Class: SftpayPaymentService.java
 * @Description:
 * @Author leo
 * @Date 2019/4/8 11:36
 * @Version
 **/
@Service
public class ShengyuPaymentService extends BasePayment {
    private final static String logPrefix = "【圣域支付】";

    // 下单
    private final static String ORDER_CREATE_STR = "/utopay/api/safepay.pay";
    // 订单查询请求串
    private final static String ORDER_QUERY_STR = "/Pay_Trade_query.html";

    @Override
    public String getChannelName() {
        return ShengyupayConfig.CHANNEL_NAME;
    }


    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case ShengyupayConfig.CHANNEL_NAME_SFT_ALIPAY_WAP:
                retObj = doOrderReq(payOrder);
                break;
            case ShengyupayConfig.CHANNEL_NAME_SFT_ALIPAY_QR:
                retObj = doOrderReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }

        return retObj;
    }

    private JSONObject doOrderReq(PayOrder payOrder) {
        ShengyupayConfig shengyupayConfig = new ShengyupayConfig(getPayParam(payOrder));
        // 请求参数
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("companyId", shengyupayConfig.getMchId());
        parameters.put("userOrderId", payOrder.getPayOrderId());
        parameters.put("payType", shengyupayConfig.getPayMode());
        parameters.put("item", ShengyupayConfig.PAY_PRODUCTNAME);
        parameters.put("fee", payOrder.getAmount());
        parameters.put("callbackUrl", payOrder.getReturnUrl());
        parameters.put("syncUrl", payConfig.getNotifyUrl(getChannelName()));
        String sign = getSign(shengyupayConfig.getMchId(),payOrder.getPayOrderId(),String.valueOf(payOrder.getAmount()),shengyupayConfig.getPrivateKey());
        parameters.put("sign",sign);
        parameters.put("ip",payOrder.getClientIp());
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);

        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.getForObject(getReqUrl(shengyupayConfig.getRequestUrl(), ORDER_CREATE_STR)+"?" + UriVariables.getMapToParameters(parameters), JSONObject.class);
        JSONObject retObj = new JSONObject();

        if (origin.getString("result").equals(ShengyupayConfig.RETURN_VALUE_SUCCESS)){
            String url = origin.getString("param");
            String payForm = getHtml(url);
            return buildPayResultOfForm(retObj, payOrder, payForm);
        }

        throw  new PayErrorException(new PayException("Invalid Arguments", "圣域支付下单失败"));
    }

    /**
     * 订单查询
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
      return null;
    }

    /**
     * 签名
     * @param companyId
     * @param userOrderId
     * @param fee
     * @param key
     * @return
     */

    private String getSign(String companyId, String userOrderId,String fee ,String key) {
        String signTxt = companyId + "_" + userOrderId + "_" + fee + "_";
        _log.info("{}签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, key, SignUtils.CHARSET_UTF8);
        return sign;
    }

    /**
     * 查询参数
     * @param orderId
     * @param key
     * @return
     */
    private String getQuerySign(String orderId,String key) {
        String signTxt = orderId +  "_";
        _log.info("{}查询签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, key , SignUtils.CHARSET_UTF8);
        return sign.toUpperCase();
    }

    //获取请求html
    private String getHtml(String payUrl){
        StringBuffer buffer = new StringBuffer();
        buffer.append("<script type=\"text/javascript\">");
        buffer.append("window.location.href=\""+payUrl+"\"");
        buffer.append("</script>");
        return buffer.toString();
    }

}
